<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="150px"
    size="small"
  >
    <!-- 基础字段和扩展字段 -->
    <template v-for="field in safeFields" :key="field.fieldName">
      <!-- 基础字段 -->
      <template v-if="field.isBaseField">
        <el-form-item
          :label="field.displayName"
          :prop="field.fieldName"
          :required="field.isRequired"
        >
          <component
            :is="getComponent(field.formComponentType)"
            v-model="formData[field.fieldName]"
            :field="field"
          ></component>
        </el-form-item>
      </template>

      <!-- 扩展字段 -->
      <template v-else>
        <el-form-item
          :label="field.displayName"
          :prop="'extFields.' + field.fieldName"
          :required="field.isRequired"
        >
          <component
            :is="getComponent(field.formComponentType)"
            v-model="formData.extFields[field.fieldName]"
            :field="field"
          ></component>
        </el-form-item>
      </template>
    </template>

    <!-- 操作按钮 -->
    <el-form-item style="margin-top: 20px">
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";

// 导入表单组件
import FormText from "./form/FormText.vue";
import FormTextarea from "./form/FormTextarea.vue";
import FormNumber from "./form/FormNumber.vue";
import FormSelect from "./form/FormSelect.vue";
import FormRadio from "./form/FormRadio.vue";
import FormDate from "./form/FormDate.vue";
//import FormSwitch from "./form/FormSwitch.vue";

// 接收父组件参数并添加类型验证
const props = defineProps({
  fields: {
    type: Array,
    default: () => [], // 确保默认值是一个空数组
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
  moduleId: {
    type: Number,
    required: true,
  },
});

// 暴露事件
const emit = defineEmits(["submit", "cancel"]);

// 表单状态
const formRef = ref(null);
const formData = ref({
  id: null,
  moduleId: props.moduleId,
  extFields: {},
});

// 表单验证规则
const formRules = ref({});

// 安全处理fields，确保它始终是一个数组
const safeFields = computed(() => {
  // 检查是否为数组，不是则返回空数组
  if (!Array.isArray(props.fields)) {
    console.warn("DynamicForm 组件接收的 fields 不是一个数组，已自动转换为空数组");
    return [];
  }
  return props.fields;
});

// 组件映射
const componentMap = {
  text: FormText,
  textarea: FormTextarea,
  number: FormNumber,
  select: FormSelect,
  radio: FormRadio,
  date: FormDate,
 // switch: FormSwitch,
};

// 获取组件
const getComponent = (type) => {
  return componentMap[type] || FormText;
};

// 初始化表单验证规则
const initFormRules = () => {
  const rules = {};

  safeFields.value.forEach((field) => {
    const propName = field.isBaseField ? field.fieldName : `extFields.${field.fieldName}`;
    rules[propName] = [];

    // 必填验证
    if (field.isRequired) {
      rules[propName].push({
        required: true,
        message: `${field.displayName}不能为空`,
        trigger: field.formComponentType === "date" ? "change" : "blur",
      });
    }

    // 长度验证
    if (field.maxLength && ["text", "textarea"].includes(field.formComponentType)) {
      rules[propName].push({
        max: field.maxLength,
        message: `最多输入${field.maxLength}个字符`,
        trigger: "blur",
      });
    }

    // 数字验证
    if (field.fieldType === "number") {
      rules[propName].push({
        type: "number",
        message: `${field.displayName}必须是数字`,
        trigger: "blur",
      });
    }
  });

  formRules.value = rules;
};

// 填充默认值
const fillDefaultValues = () => {
  safeFields.value.forEach((field) => {
    if (!field.isBaseField) {
      // 确保扩展字段存在
      if (!formData.value.extFields) {
        formData.value.extFields = {};
      }

      // 如果字段未定义，设置默认值
      if (formData.value.extFields[field.fieldName] === undefined) {
        switch (field.fieldType) {
          case "string":
            formData.value.extFields[field.fieldName] = "";
            break;
          case "number":
            formData.value.extFields[field.fieldName] = null;
            break;
          case "boolean":
            formData.value.extFields[field.fieldName] = false;
            break;
          case "date":
            formData.value.extFields[field.fieldName] = null;
            break;
          default:
            formData.value.extFields[field.fieldName] = "";
        }
      }
    }
  });
};

// 初始化表单数据
const initFormData = () => {
  // 基础数据
  formData.value = {
    ...props.initialData,
    moduleId: props.moduleId,
    extFields: props.initialData.extFields || {},
  };

  // 填充默认值
  fillDefaultValues();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    emit("submit", { ...formData.value });
  } catch (error) {
    // 表单验证失败
    return false;
  }
};

// 取消操作
const handleCancel = () => {
  emit("cancel");
};

// 监听字段变化，重新初始化表单
watch(
  () => props.fields,
  () => {
    initFormRules();
    initFormData();
  },
  { deep: true }
);

// 组件挂载时初始化
onMounted(() => {
  initFormRules();
  initFormData();
});
</script>

<style scoped>
/* 动态表单样式 */
::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
